$(function(){
    // 初始化加载学生列表
    loadStudentList();

    // 绑定查询按钮点击事件
    $("#searchBtn").click(function(){
        loadStudentList();
    });

    // 绑定回车键触发查询
    $("#searchForm input").keypress(function(e){
        if(e.which == 13) {
            loadStudentList();
        }
    });
});

function loadStudentList(){
    // 获取查询表单数据
    let searchParams = $("#searchForm").serialize();

    $.ajax({
        url: "/api/student/list?" + searchParams
    }).done(function(data) {
        let html = "";
        data.forEach((element,index) => {
            html += "<tr>";
            html += "<td>"+ element.id +"</td>";
            html += "<td>"+ element.name +"</td>";
            html += "<td>"+ (element.sex === 1 ? "男" : "女") +"</td>";
            html += "<td>"+ element.age +"</td>";
            html += "<td>"+ element.tno+"</td>";
            html += "<td><a href='#' onclick='showStudentDlg("+element.id+")'>编辑</a> &nbsp;&nbsp;<a href='#' onclick='deleteById("+element.id+")'>删除</a></td>";
            html += "</tr>";
        })
        $("#studentTb").html(html);
    });
}

let layerIndex;

/**
 * 弹出学生新增/更新对话框
 */
function showStudentDlg(id) {
    let title = "新增学生";
    if(id){
        // 是编辑
        title = "编辑学生";
        $("#formId").css("display", "block");

        // 读取学生信息，并赋值
        $.ajax({
            url: "/api/student/" + id,
            method: "GET",
        }).done(result => {
            console.log(result);
            // 填充表单数据
            $("#id").val(result.id);
            $("#name").val(result.name);
            $("input[name='sex'][value='" + result.sex + "']").prop("checked", true);
            $("input[name='age']").val(result.age);
            $("input[name='tno']").val(result.tno);

            // 重新渲染表单
            layui.form.render();
        });
    } else {
        // 是新增
        $("#studForm")[0].reset();
        $("#formId").css("display", "none");
    }

    layerIndex = layer.open({
        type: 1,
        title: title,
        area: ["520px", "auto"],
        content: $("#studForm")
    });
}

layui.use(['form', 'layer'], function(){
    var form = layui.form;
    var layer = layui.layer;

    // 表单提交验证
    form.on("submit(stud-dlg)", function(data) {
        commitStuDlg();
        return false; // 阻止表单跳转
    });
});

function commitStuDlg(){
    let id = $("#id").val();
    let formData = {
        id: id,
        name: $("input[name='name']").val(),
        sex: $("input[name='sex']:checked").val(),
        age: $("input[name='age']").val(),
        tno: $("input[name='tno']").val()
    };

    $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled");

    if(id && id !== ""){
        // 更新学生
        $.ajax({
            url: "/api/student/update",
            method: "PUT",
            contentType: "application/json",
            data: JSON.stringify(formData)
        }).done(result => {
            if(result.id){
                loadStudentList();
                layer.close(layerIndex);
            }
        }).fail(error => {
            console.error("更新失败:", error);
            alert("更新失败，请重试！");
            $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
        });
    } else {
        // 新增学生
        $.ajax({
            url: "/api/student/add",
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify(formData)
        }).done(result => {
            if(result.id){
                loadStudentList();
                layer.close(layerIndex);
            }
        }).fail(error => {
            console.error("新增失败:", error);
            alert("新增失败，请重试！");
            $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
        });
    }
}

function deleteById(id) {
    layer.confirm('确定要删除这条记录吗？', {icon: 3, title:'删除确认'}, function(index){
        $.ajax({
            url: "/api/student/delete/" + id,
            method: "DELETE"
        }).done(result => {
            loadStudentList();
            layer.msg('删除成功', {icon: 1});
        }).fail(error => {
            console.error("删除失败:", error);
            layer.msg('删除失败', {icon: 2});
        });
        layer.close(index);
    });
}